//	仪表盘图

import React from 'react';
import { Gauge, GaugeOptions } from '@antv/g2plot';
import { WD_TYPE } from 'src/pages/AnalyseManage/EditReport/components/EditorDataType/EnumConfig';
import { getComponentData } from 'src/services/AnalyseManage';
import { ChartService, IProps } from 'src/pages/AnalyseManage/EditReport/components/ChartsType/components/ChartService';
import { digitFormat, isNumber } from 'src/libs/utils';

export default class GaugeChart extends ChartService {

	state = {
		chartEl: null,
		name: '指标',
		percent: 0.65,
		// blockColor: 'l(0) 0:#F4664A 0.6:#FAAD14 1:#30BF78'
		blockColor: {
			// gaugeColorBlock1: '#F4664A',
			// gaugeColorBlock2: '#FAAD14',
			// gaugeColorBlock3: '#30BF78',
			gaugeColorBlock1: '#31D4A8',
			gaugeColorBlock2: '#31D4A8',
			gaugeColorBlock3: '#31D4A8',
		},
		eventToken: [],
		dependencies: [],	//	图表联动参数
		isRender: false
	};

	getBlockColor = () => {
		//	区间颜色: 'l(0) 0:#F4664A 0.6:#FAAD14 1:#30BF78'
		let color = 'l(0)';
		// let blockValue = [ 0, 0.6, 1 ];	//	区间值颜色分段
		/* Object.keys( this.state.blockColor ).map( ( v, i ) => {
			let itemColor = this.props.config.style[ v ] || this.state.blockColor[ v ];
			color += ` ${ blockValue[ i ] }:${ itemColor }`;
			return color;
		} );
		return color; */
		let colorArr = Object.keys( this.state.blockColor ).map( ( v, i ) => {
			let itemColor = this.props.config.style[ v ] || this.state.blockColor[ v ];
			return itemColor;
		} );
		let percent = this.state.percent;
		color = percent < 0.6 ? colorArr[0] : percent < 0.8 ? colorArr[1] : colorArr[2];
		return color;
	};

	getConfig = (): GaugeOptions => {
		let { config } = this.props;
		return {
			percent: this.state.percent,
			autoFit: true,
			appendPadding: [ 20, 50, 40, 50 ],
			range: {
				// ticks: [ 0, 1 ],
				color: this.getBlockColor()
			},
			indicator: config.style.hiddenScale ? null : {
				pointer: {
					style: {
						lineCap: 'round',
						lineWidth: 5,
						// stroke: '#D0D0D0'
						stroke: '#FFBB22'
					},
				},
				pin: {
					style: {
						fill: '#fff',
						lineWidth: 4.5,
						r: 9.75,
						// stroke: '#D0D0D0'
						stroke: '#FFBB22'
					},
				},
			},
			axis: {
				label: {
					formatter( v ) {
						return v;
					},
				},
				subTickLine: {
					count: 3,
				},
			},
			statistic: {
				title: config.style.isShowValue === false ? false : {
					formatter: () => `${ this.state.percent }`,
					style: {
						textAlign: 'center',
						fontFamily: config.style.valueFontFamily || 'inherit',
						fill: config.style.valueFontColor || '#31D4A8',
						fontSize: config.style.valueFontSize || 32,
						fontWeight: config.style.valueFontBold ? 'bold' : 'normal',
						fontStyle: config.style.valueFontItalic ? 'italic' : 'normal',
					},
					offsetY: 30
				},
				content: config.style.isShowLabel === false ? false : {
					formatter: () => this.state.name,
					style: {
						textAlign: 'center',
						fontFamily: config.style.labelFontFamily || 'inherit',
						// fill: config.style.labelFontColor || '#999',
						color: config.style.labelFontColor || '#999',
						fontSize: config.style.labelFontSize || 15,
						fontWeight: config.style.labelFontBold ? 'bold' : 'normal',
						fontStyle: config.style.labelFontItalic ? 'italic' : 'normal',
						opacity: 1,
					},
					offsetY: -5,
				},
			}
		};
	}

	async getConditionData() {
		let { config } = this.props;

		if ( config.data.measure && config.data.measure.length > 0 ) {
			const x = config.data.measure.map( v => {
				return {
					aggregateType: v.aggregateType,	//	度量的聚合类型
					formatType: '',	// 维度的聚合类型
					alias: v.title,
					dataType: v.dataType,
					frontendId: '',
					id: v.name,
					orderType: v.orderType,	//	排序方式
					quota: v.modelType === WD_TYPE ? 'WD' : 'DL',
					symbol: '',
					type: v.type,
					value: '',
					dataUnit: v.dataUnit || '',
					precision: v.precision
				};
			} );

			//	筛选字段
			const filterConditions = this.props.config.data.filterFields
				? this.props.config.data.filterFields.map( ( v ) => v.filterConditions ).flat()
				: [];

			// 筛选组件的 condition
			let filterCompConditions = this.props.config.data.filterConditions || {};
			let newFilterCompConditions = [];
			Object.keys( filterCompConditions ).forEach( ( key ) => {
				newFilterCompConditions = newFilterCompConditions.concat( filterCompConditions[key] );
			} );


			const request = {

				dataConfig: {
					dataModel: {
						pageId: this.props.pageId,
						tableName: config.data.tableCode,
						x: x,
						conditions: filterConditions.concat( this.state.dependencies, newFilterCompConditions )
					},
					needAutoRefresh: true,
					tableType: 'Dashboard'
				},
				type: 'quota',
				tenantCode: this.props.tenantCode
			};

			let pageResponse = await getComponentData( request );
			if ( pageResponse.data && pageResponse.data.success && pageResponse.data.data.rows && pageResponse.data.data.rows.length > 0 ) {
				let info = pageResponse.data.data.rows[ 0 ];
				if ( info ) {
					let key = Object.keys( info )[ 0 ];
					let value = info[ key ];
					const unit = info.dataUnit || '';
					const precision = info.precision || '';
					value = isNumber( precision ) ? value.toFixed( precision ) : value;
					this.setState( {
						name: key,
						percent: value ? `${digitFormat( value, 3 )}${unit}` : value
					} );
				}

			}
		}

	}

	shouldComponentUpdate( nextProps: Readonly<IProps>, nextState: Readonly<{ name: string; percent: number, dependencies: any }>, nextContext: any ): boolean {
		if ( JSON.stringify( nextProps ) !== JSON.stringify( this.props ) ||
			this.state.name !== nextState.name ||
			this.state.percent !== nextState.percent ||
			JSON.stringify( this.state.dependencies ) !== JSON.stringify( nextState.dependencies )
		) return true;
		return false;
	}


	getSnapshotBeforeUpdate( prevProps: Readonly<IProps>, prevState: Readonly<{dependencies: any}> ): any | null {
		let { config, chartLayout } = this.props;
		let changeObj = Object.create( null );

		//	判断数据字段是否变化了
		if ( JSON.stringify( prevProps.config.data ) !== JSON.stringify( config.data ) || JSON.stringify( this.state.dependencies ) !== JSON.stringify( prevState.dependencies ) ) {
			changeObj.needDataChange = true;
		}

		//	判断样式是否改变
		if ( JSON.stringify( prevProps.config.style ) !== JSON.stringify( config.style ) ) {
			changeObj.needStyleChange = true;
		}

		//判断是否因宽高改变重新适应布局
		if ( prevProps.chartLayout.w !== chartLayout.w || prevProps.chartLayout.h !== chartLayout.h ) {
			changeObj.needLayoutChange = true;
		}

		return changeObj;

	}

	initEvent = async () => {
		await this.getConditionData();

		const gauge = new Gauge( this.props.id, this.getConfig() );
		gauge.render();

		this.setState( {
			chartEl: gauge,
			isRender: true
		} );
	};

	async componentDidUpdate( prevProps: Readonly<IProps>, prevState: Readonly<{}>, snapshot?: any ) {
		if( !snapshot ) return;
		if ( snapshot.needStyleChange ) this.state.chartEl.update( this.getConfig() );

		if ( snapshot.needDataChange ) {
			await this.getConditionData();
			this.state.chartEl.changeData( this.state.percent );

		}
	}

	render() {
		return <div id={ this.props.id } style={ { height: '100%' } }></div>;
	}

};
